package com.wsdcd.zlg.controller;

import com.wsdcd.zlg.core.exception.ERPException;
import com.wsdcd.zlg.model.entity.Product;
import com.wsdcd.zlg.model.service.ProductService;
import com.wsdcd.zlg.util.AjaxObject;
import com.wsdcd.zlg.util.PageParameter;
import com.wsdcd.zlg.util.PagerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;

@AllArgsConstructor
@Controller
@RequestMapping("/product")
public class ProductController {
	private final ProductService productService;
	private final HttpServletRequest request;

	@RequestMapping("list")
	public String userList() {
		return "product/list";
	}

	@ResponseBody
	@RequestMapping("lists")
	public PagerUtil<Product> orderLists(int page,int limit,String searchType,String searchValue) {
		if(searchValue != null){
			searchValue = searchValue.trim();
		}
		PageParameter pageParameter = new PageParameter(page,limit,searchType,searchValue);
		return productService.selectByPage(pageParameter);
	}
	
	@RequestMapping("add")
	public String add() throws ServletException, IOException {
		return "product/add";
	}

	@ResponseBody
	@RequestMapping("adds")
	public AjaxObject adds(Product product) {
		try {
			productService.insert(product);
			String msg = "添加成功";
			return new AjaxObject(1, msg);
		} catch (ERPException e) {
			String msg = e.getMessage();
			return new AjaxObject(0, msg);
		}
	}
	
	@RequestMapping("update")
	public String update(String productId, Model model)
			throws ServletException, IOException {
		Product product = productService.selectByProductId(productId);
		model.addAttribute("updateProduct", product);
		return "product/update";
	}

	@ResponseBody
	@RequestMapping("updates")
	public AjaxObject updates(Product product) {
		String productIdString = request.getParameter("productId");
		int productId = Integer.parseInt(productIdString);
		product.setProductId(productId);
		try {
			productService.update(product);
			String msg = "修改成功";
			return new AjaxObject(1, msg);
		} catch (ERPException e) {
			String msg = e.getMessage();
			return new AjaxObject(0, msg);
		}
	}

	@ResponseBody
	@RequestMapping("deleteAll")
	public AjaxObject deleteAll(String productIds)
			throws ServletException, IOException {
		if(productIds == null || productIds.trim().equals("")){
			String msg = "删除失败，请传递数据";
			return new AjaxObject(0, msg);
		}
		String[] arr = productIds.split(",");
		int[] array = Arrays.stream(arr).mapToInt(Integer::parseInt).toArray();
		try {
			productService.deleteAll(array);
			String msg = "删除成功";
			return new AjaxObject(1, msg);
		} catch (ERPException e) {
			String msg = e.getMessage();
			return new AjaxObject(0, msg);
		}
	}
	
}
